#!/bin/bash

SUDO="sudo"

function check_permission()
{
	if [ ${UID} -eq 0 ];then
		SUDO=
	fi
}

# check if returns not be expect value, will exit script
# ${1}=caller line
# ${2}=return value
# ${3}=expect value
function check_retnot_exit()
{
	# target caller line
	callerline=${1}

	# return integer value
	rv=${2}

	# expect integer value (0,1,...,etc)
	ev=${3}

	if [ ${rv} -ne ${ev} ];then
		echo "err:line:${callerline} failed"
		exit 1
	fi
}

function check_network()
{
	host www.baidu.com 1>/dev/null 2>/dev/null
	ret=$?
	return ${ret}
}

function install_vim()
{
	${SUDO} apt-get install -y vim vim-gtk3
    if [[ $? -ne 0 ]];then
        echo "apt无法安装vim，请手动从源码安装vim，然后修改此 setup.sh 跳过此步骤"
        exit 1
    fi
}

function install_bundle()
{
	git clone https://github.com/VundleVim/Vundle.vim ~/.vim/bundle/Vundle.vim
}

function install_config_bundle()
{
	cat /dev/null > ~/.vimrc
	cat >~/.vimrc<<EOF
">>>>>> this is configure for bundle
set nocompatible              " be iMproved, required
filetype off                 	     " required

set nocompatible              " be iMproved, required
filetype plugin on

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required
" To ignore plugin indent changes, instead use:
"filetype plugin on
"
" Brief help
" :PluginList       - lists configured plugins
" :PluginInstall    - installs plugins; append \`!\` to update or just :PluginUpdate
" :PluginSearch foo - searches for foo; append \`!\` to refresh local cache
" :PluginClean      - confirms removal of unused plugins; append \`!\` to auto-approve removal
"
" see :h vundle for more details or wiki for FAQ
" Put your non-Plugin stuff after this line
EOF
}

function install_ctags_cscope()
{
    # 尝试安装 ctags
	${SUDO} apt-get install -y ctags
    if [[ $? -ne 0 ]];then
        ${SUDO} apt-get install -y universal-ctags

        if [[ $? -ne 0 ]];then
            ${SUDO} apt-get install -y exuberant-ctags

            if [[ $? -ne 0 ]];then
                echo "apt无法安装ctags，请手动从源码安装ctags，然后修改此 setup.sh 跳过此步骤"
                exit 1
            fi
        fi
    fi

    # 安装 cscope
    ${SUDO} apt-get install -y cscope

    # 检查其他工具
    which split > /dev/null 2>&1
    if [[ $? -ne 0 ]];then
        echo "需要用到 split 命令但系统里没有，需要想办法安装，然后修改此 setup.sh 跳过此步骤"
        exit 1
    fi

}

function install_plugin_github()
{
	dir_cur=`pwd`
	cd ~/.vim/bundle

	#git clone https://github.com/vim-scripts/cscope_dynamic
	#set rtp+=${HOME}/.vim/bundle/cscope_dynamic

	#git clone https://github.com/vim-scripts/autoload_cscope.vim
	#set rtp+=${HOME}/.vim/bundle/autoload_cscope.vim

	cd ${dir_cur}
}

function install_plugin_bundles()
{

	cat >> ~/.vimrc << EOF

">>>>>> this is configure for bundle install list
Bundle 'taglist.vim'
Bundle "scrooloose/nerdtree" 
Bundle "wesleyche/SrcExpl" 
Bundle "majutsushi/tagbar"
Bundle "luochen1990/rainbow"
EOF
}

function install_plugin_runtimepath()
{
	cat >> ~/.vimrc << EOF
set rtp+=${HOME}/.vim/bundle/comments.vim
set rtp+=${HOME}/.vim/bundle/mark.vim
set rtp+=${HOME}/.vim/bundle/lookupfile
set rtp+=${HOME}/.vim/bundle/genutils
set rtp+=${HOME}/.vim/bundle/minibufexpl

set rtp+=${HOME}/.vim/bundle/taglist.vim
set rtp+=${HOME}/.vim/bundle/nerdtree
set rtp+=${HOME}/.vim/bundle/SrcExpl
set rtp+=${HOME}/.vim/bundle/tagbar
set rtp+=${HOME}/.vim/bundle/rainbow
set rtp+=${HOME}/.vim/bundle/indentLine/after
set rtp+=${HOME}/.vim/bundle/code_complete

EOF
}

function install_common_vimrc()
{
	cat >> ~/.vimrc << EOF

">>>>>> vimrc common settings
"   界面配置
set ttyfast
set completeopt=longest,menu    "让Vim的补全菜单行为与一般IDE一致
set statusline=\ %%F%m%r%h[%{(&fenc==\"\")?&enc:&fenc}%{(&bomb?\",BOM\":\"\")}]\ %w\ \ CWD:\ %r%{getcwd()}%h\ \ \ [POS(%P):%l/%L,%c]
set laststatus=1    "命令行高度,默认1
set number          "显示行号&nonumber
set ruler           "显示当前位置坐标
set hlsearch        "搜索高亮&nohlsearch
set ignorecase      "搜索模式里忽略大小写
set smartcase       "如果搜索模式包含大写字符
set incsearch       "开启搜索实时匹配功能&noincsearch
set wrap            "限制（长行显示关闭; nowrap-->打开）
set mousehide   "Hide the mouse cursor while typing
set t_ti= t_te= "设置退出vim时保留当前画面(防误删)
set mouse=a        "mouse=a启用鼠标;mouse-=a 关闭鼠标
set scrolloff=0     " 在上下移动光标时，光标的上方或下方至少会保留显示的行数
set showmatch       " 括号配对情况, 跳转并高亮一下匹配的括号
set showcmd         " 在状态栏显示正在输入的命令
set showmode        " 左下角显示当前vim模式
""set cursorcolumn    " 突出显示当前列
""set cursorline      " 突出显示当前行
set autoindent
set smartindent
set tabstop=4
set shiftwidth=4
"   对齐配置
filetype plugin indent on       "启动自动对齐
filetype indent on              "针对不同的文件类型采用不同的缩进格式
set autoindent  "自动缩进
set smartindent "智能缩进
set tabstop=4       " 设置Tab键的宽度        [等同的空格个数]
set shiftwidth=4    " 每一次缩进对应的空格数
set softtabstop=4  " 按退格键时可以一次删掉 4 个空格
set smarttab
"set expandtab       " 将Tab自动转化成空格,需要输入Tab时，使用Ctrl+V + Tab
set shiftround      " 缩进时，取整


"theme主题
"set background=dark
"set t_co=256
"设置标记一列的背景颜色和数字一行颜色一致
"hi! link signcolumn   linenr
"hi! link showmarkshll diffadd
"hi! link showmarkshlu diffchange
"for error highlight，防止错误整行标红导致看不清
"highlight clear spellbad
"highlight spellbad term=standout ctermfg=1 term=underline cterm=underline
"highlight clear spellcap
"highlight spellcap term=underline cterm=underline
"highlight clear spellrare
"highlight spellrare term=underline cterm=underline
"highlight clear SpellLocal
"highlight SpellLocal term=underline cterm=underline

"   文件配置
filetype on                     "检测文件类型
syntax enable                   "syntax switch enable
syntax on                       "syntax switch on
set wildignore=*.o,*~,*.pyc,*.class,*.swp,*.bak     "Ignore compiled files
set nocp    "vi compatible mode 该功能每次修改保存文件时自动插入头文件
set nobackup        "关闭自动备份
set autoread        "文件修改之后自动载入
set noswapfile      "关闭交换文件
set wildmenu        "增强模式中的命令行自动完成操作
"set autochdir     "自动改变当前目录位置autochdir or noautochdir

" 禁止Vim自动切换工作目录（核心配置）
set noautochdir
" 可选：显示当前工作目录（方便确认）
" 打开Vim时显示
"echom "当前工作目录: " . getcwd()
" 也可以设置状态栏显示（需要状态栏插件支持，如lightline、lualine等）
"set statusline+=\ %{getcwd()}


" 解析INI文件并获取指定section下的key值
" 参数:
"   ini_file: INI文件路径
"   section: 要查找的节名(如[General])
"   key: 要查找的键名(如workdir)
function! s:GetIniValue(ini_file, section, key)
    " 检查文件是否存在
    if !filereadable(a:ini_file)
        echom "INI文件不存在: " . a:ini_file
        return ""
    endif

    let l:section_found = 0
    let l:file = readfile(a:ini_file)

    " 逐行解析文件
    for l:line in l:file
        " 去除首尾空格
        let l:line = trim(l:line)
        
        " 跳过空行和注释(;或#开头)
        if l:line == "" || l:line[0] == ';' || l:line[0] == '#'
            continue
        endif

        " 检查节名(如[section])
        if l:line[0] == '[' && l:line[-1] == ']'
            let l:current_section = trim(l:line[1:-2])
            let l:section_found = (l:current_section == a:section)
            continue
        endif

        " 当找到目标节时,查找key
        if l:section_found
            let l:pair = split(l:line, '=', 1) " 按第一个=分割
            if len(l:pair) == 2
                let l:current_key = trim(l:pair[0])
                if l:current_key == a:key
                    return trim(l:pair[1]) " 返回key对应的值
                endif
            endif
        endif
    endfor

    " 未找到对应key
    echom "在INI文件中未找到 " . a:section . " 节下的 " . a:key
    return ""
endfunction

" 从INI更新工作目录的函数
"function! s:UpdateWorkdirFromIni()
"    let g:workdir = "/home/rlk/Desktop/vimkernel/u-boot-xlnx-xilinx-v2020.2-zu48dr"
"
"    if g:workdir != ""
"        let g:expanded_workdir = expand(g:workdir)
"        if isdirectory(g:expanded_workdir)
"            let l:current_dir = getcwd()
"            " 仅在目录不同时才切换，避免不必要的操作
"            if l:current_dir != g:expanded_workdir
"                cd {g:expanded_workdir}
"                echom "工作目录已更新为: " . getcwd()
"            endif
"        else
"            echom "配置的workdir不存在: " . g:expanded_workdir
"        endif
"    endif
"endfunction

" 1. 启动时初始化工作目录
"call s:UpdateWorkdirFromIni()

" 2. 切换文件时自动更新（BufEnter事件在缓冲区加载后触发）
"augroup AutoUpdateWorkdir
"    autocmd!
"    " 对所有文件类型生效
"    autocmd BufEnter * call s:UpdateWorkdirFromIni()
"    " 可选：仅对特定文件类型生效（如代码文件）
"    " autocmd BufEnter *.cpp,*.h,*.py call s:UpdateWorkdirFromIni()
"augroup END






set encoding=utf-8  " 设置新文件的编码为 UTF-8
" 注：使用utf-8格式后，软件与程序源码、文件路径不能有中文，否则报错
set fileencodings=ucs-bom,utf-8,gbk,cp936,gb18030,big5
set fileencodings+=euc-jp,euc-kr,latin1,latin-1 " 设置支持打开的文件的编码
set termencoding=utf-8  " 下面这句只影响普通模式 (非图形界面) 下的 Vim
set formatoptions+=m    " 如遇Unicode值大于255的文本，不必等到空格再折行
set formatoptions+=B    " 合并两行中文时，不在中间加空格
set fileencoding=utf-8  "设置当前文件编码，可以更改
set ffs=unix,dos,mac    " 文件格式，默认 ffs=dos,unix
set fileformat=unix "设置新文件的<EOL>格式，dos（windows系统常用）
set fileformats=unix,dos,mac    "给出文件的<EOL>格式类型
"set backup
"set backupext=.bak
"set backupdir=/tmp/vimbk/


"插入模式下方向键的使用
imap <c-k> <Up>
imap <c-j> <Down>
imap <c-h> <Left>
imap <c-l> <Right>
"
"成对符号自动匹配
:inoremap " ""<ESC>i
:inoremap ' ''<ESC>i
:inoremap [ []<ESC>i
:inoremap < <><ESC>i
"
"
"关闭方向键方向功能:使用hjkl
"map <Left> <Nop>
"map <Right> <Nop>
"map <Up> <Nop>
"map <Down> <Nop>

" 删除多余空行
:nmap cl :1,$g/^$/d
" 删除行尾空格和tab符号
:nmap cs :1,$s/\s\+$//g
:nmap ct :1,$s/\t\+$//g
" 删除行尾^M符号
:nmap cm :1,$s/\r//g


EOF
}

function install_config_taglist()
{
	cat >> ~/.vimrc << EOF


">>>>>> taglist setting
filetype on
nmap <F5> :TlistToggle<CR>        "F5 Key = Tag list Toggling
let Tlist_Ctags_Cmd = "/usr/bin/ctags"    " whereis ctags
let Tlist_Inc_WinWidth = 0        "window width change off"
let Tlist_Exit_OnlyWindow = 0        
let Tlist_Auto_Open = 0            "VIM打开时
let Tlist_Use_Right_Window = 1


"autocmd 事件参数 匹配模式 :需要执行的命令、函数或脚本
"下列意思是，在启动vim时，自动执行指定命令"
"autocmd VimEnter * :cscope add cscope.out
"autocmd VimEnter * :set tags=tags
"autocmd VimEnter * :set tags+=${HOME}/.vim/systags
"autocmd VimEnter * :let g:LookupFile_TagExpr = '"filenametags"'

"退出vim编辑器时,根据是否创建工程来决定是否保存会话文件
function! s:DirectoryExists(directory)
    let l:directory = fnamemodify(a:directory, ':p')
    return isdirectory(l:directory) == 1
endfunction

"退出vim编辑器时,根据是否创建工程来决定是否保存会话文件
"set sessionoptions=buffers,curdir,resize,folds,tabpages
let g:vim_workdir = getcwd()
let g:vim_projdir = g:vim_workdir . '/vim_project'
"如果存在此目录,才保存相关的会话文件
if s:DirectoryExists(g:vim_projdir)
    autocmd VimLeave * :echom "保存窗口布局至:" . g:vim_projdir . "/vim_session.vim"
    let sessionfile = g:vim_projdir . "/vim_session.vim"

    " 使用execute解析变量，将命令字符串拼接后执行
    autocmd VimLeave * execute 'mks! ' . fnameescape(sessionfile)
    "autocmd VimLeave * :mks! sessionfile
endif

" 定义自动加载会话的函数
function! s:LoadSessionOnStart()
    let sessionfile = g:vim_projdir . "/vim_session.vim"

    " 检查会话文件是否存在
    if filereadable(sessionfile)
        " 加载会话文件
        execute 'source ' . fnameescape(sessionfile)
        echom "已自动加载上次窗口布局: " . sessionfile
    endif
endfunction

" 定义自动加载工程数据库文件的函数
function! s:LoadCscopeOnStart()
    let cscopefile = g:vim_projdir . "/vim_project_preload.vim"

    " 加载ctags、cscope等文件

    " 检查文件是否存在
    if filereadable(cscopefile)
        " 加载会话文件，等同于 vim -s vim_project/vim_project_preload.vim 这个操作
        execute 'source ' . fnameescape(cscopefile)
        echom "当前工作目录: " . g:vim_workdir
        "echom "已自动加载工程数据库: " . cscopefile
    endif
endfunction

" 当Vim完全启动后执行会话加载
augroup AutoLoadSession
	 " 清除已有自动命令，避免重复加载
     autocmd!
     autocmd VimEnter * call s:LoadSessionOnStart()
     autocmd VimEnter * call s:LoadCscopeOnStart()
augroup END


" 检查是否是工程目录，只有存在工程目录才会执行分支里的逻辑
if s:DirectoryExists(g:vim_projdir)

    " 保存时自动执行命令的插件
    " 防止重复定义自动命令，先清除已存在的同名组
    augroup AutoSaveCommands
        " 清除已有自动命令，避免重复加载
        autocmd!
        " BufWritePost: 文件保存后触发
        " *: 对所有文件类型生效
        autocmd BufWritePost * call s:OnFileSaved()
    augroup END 


    " 定义保存后执行的函数
    function! s:OnFileSaved()
        " 获取当前文件名
        let current_file = expand('%:p')
        let file_type = &filetype

        " 根据文件类型执行不同的命令
        "if file_type == 'python'
        "elseif file_type == 'javascript'
        "elseif file_type == 'c' || file_type == 'cpp'

        " 显示保存成功的提示
        "echom '文件已保存: ' . current_file . " " . strftime('%Y-%m-%d %H:%M:%S')
        echom strftime('%Y-%m-%d %H:%M:%S') . ' ' . "更新工程文件: ..."

        " 更新工程文件，执行外部命令(阻塞方式执行)
        let cmd = 'vim_project_update.elf ' . g:vim_workdir . " clean_objs"
        let output = system(cmd)
        let cmd = 'vim_project_update.elf ' . g:vim_workdir
        let output = system(cmd)
        echom strftime('%Y-%m-%d %H:%M:%S') . ' ' . "更新工程文件: 完成"


        " 自动载入工程文件
        echom strftime('%Y-%m-%d %H:%M:%S') . ' ' . "自动载入工程文件: ..."
        call VimProject_Reload()
        echom strftime('%Y-%m-%d %H:%M:%S') . ' ' . "自动载入工程文件: 完成"

    endfunction

    " 插件初始化信息
    "echom 'AutoSaveCommands插件已加载 - 保存文件时将自动执行额外命令'
    
endif



"nmap <C-P>s :cs find s <C-R>=expand("<cword>")<CR><CR>
"nmap <C-P>g :cs find g <C-R>=expand("<cword>")<CR><CR>
"nmap <C-P>c :cs find c <C-R>=expand("<cword>")<CR><CR>
"nmap <C-P>t :cs find t <C-R>=expand("<cword>")<CR><CR>
"nmap <C-P>e :cs find e <C-R>=expand("<cword>")<CR><CR>
"nmap <C-P>f :cs find f <C-R>=expand("<cfile>")<CR><CR>
"nmap <C-P>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR>
"nmap <C-P>d :cs find d <C-R>=expand("<cword>")<CR><CR>

EOF
}

function install_config_sourceexplorer()
{
	cat >> ~/.vimrc << EOF

">>>>>> Source Explorer Setting
nmap <F4> :SrcExplToggle<CR>
let g:Srcexpl_winHeight = 8
" // Set 600 ms for refreshing the Source Explorer
let g:SrcExpl_refreshTime = 600
" // Set "Enter" key to jump into the exact definition context
""let g:SrcExpl_jumpKey = "<ENTER>"
" // Set "Space" key for back  the definition context
""let g:SrcExpl_gobackKey = "<SPACE>"
nmap <C-I> <C-W>j:call g:SrcExpl_Jump()<CR>
nmap <C-B> :call g:SrcExpl_GoBack()<CR>
let g:SrcExpl_isUpdateTags = 0

EOF
}

function install_config_nerdtree()
{
	cat >> ~/.vimrc << EOF

">>>>>> NERD Tree Setting
let NERDTreeWinPos="left"
nnoremap <F2> :NERDTreeToggle<CR>
EOF
}

function install_config_lookupfile()
{
	cat >> ~/.vimrc << EOF

">>>>>> LookupFile Setting
"let g:LookupFile_TagExpr = './filenametags'
let g:LookupFile_MinPatLength = 2               "最少输入2个字符才开始查找
let g:LookupFile_PreserveLastPattern = 0        "不保存上次查找的字符串
let g:LookupFile_PreservePatternHistory = 1     "保存查找历史
let g:LookupFile_AlwaysAcceptFirst = 1          "回车打开第一个匹配项目
let g:LookupFile_AllowNewFiles = 0              "不允许创建不存在的文件
let g:LookupFile_RecentFileListSize = 30
let g:LookupFile_FileFilter = '\.class$\|\.o$\|\.obj$\|\.exe$\|\.jar$\|\.zip$\|\.war$\|\.ear$'
"绑定快捷键F3，启动文件查找
nmap <F3> :LookupFile<CR>
EOF
}

function install_config_rainbow()
{
	cat >> ~/.vimrc << EOF

let g:rainbow_active = 1 "via :RainbowToggle

EOF
}

function install_plugin_rainbow()
{
	echo ""
}

function install_config_indentline()
{
	cat >> ~/.vimrc << EOF

" 地址: https://github.com/Yggdroot/indentLine
let g:indentLine_enabled = 1
let g:indentLine_char = '|'
let g:indentLine_color_term = 239

"Note: indentLine不支持以 Tab 为缩进的对齐线显示, 只支持以空格缩进的对齐线显示

" 针对所有 .c 文件设置缩进规则
"autocmd FileType c setlocal tabstop=4       " Tab 显示宽度为 4 列
"autocmd FileType c setlocal expandtab       " 使用空格替代 Tab
"autocmd FileType c setlocal shiftwidth=4    " 自动缩进和手动缩进（>>/<<）的宽度为 4 列
"autocmd FileType c setlocal softtabstop=4   " 按 Tab 键时实际插入的空格数为 4
"autocmd FileType c :%retab!                 " 如果原先是tab,则替换成空格
"autocmd FileType c setlocal noexpandtab       " 使用 Tab 替代空格
"autocmd FileType c :%retab!                 " 如果原先是空格,则替换成 tab

" 针对 Makefile 和 .mk 文件保留 Tab（不转换为空格）
"autocmd FileType make setlocal noexpandtab  " 保留 Tab 字符（Makefile 依赖 Tab 缩进）
"autocmd FileType make setlocal tabstop=8    " Makefile 通常使用 8 列 Tab（可按需调整）

" 打开 .c 文件时(当读取 .c 文件并加载完成后触发)自动转换缩进（仅首次打开时执行）
"autocmd BufReadPost *.c retab!

EOF
}

function install_config_minibufexpl()
{
	cat >> ~/.vimrc << EOF

" 功能: 文件名缓冲区窗口插件
" 地址: https://github.com/fholgado/minibufexpl.vim
" 用法: 如下
" b 3   跳转到3号标签文件
" bd 3  删除3号标签文件名缓冲区
" bd 1 2 3  删除1,2,3号标签文件名缓冲区
" bfirst    跳转到第一个文件名缓冲区
" blast     跳转到最后一个文件名缓冲区
" bprevious 跳转到上一个文件名缓冲区
" bnext     跳转到下一个文件名缓冲区

EOF
}

function install_config_mark()
{
	cat >> ~/.vimrc << EOF

" 功能: 代码高亮标签标注
" 地址: https://github.com/Tuxdude/mark.vim
" 用法: 命令模式下光标选中或停留在某个单词或词块上, 输入【,m】即可标注，相同词块再输入【,m】即可取消标注
let g:mapleader = ","

EOF
}

function install_config_comments()
{
	cat >> ~/.vimrc << EOF

" 功能: 代码批量注释插件
" 地址: https://github.com/sudar/comments.vim
" 用法: <Ctrl-c>注释, <Ctrl-x>取消注释


" 代码折叠,该功能尤其对于那些行数比较多的宏分支有用
set foldenable

" 代码折叠方式: manual(手工折叠), indent(用缩进表示折叠), expr(用表达式来定义折叠), syntax(用语法高亮来定义折叠), marker(用标志折叠), diff(对没有更改的文本进行折叠)
set foldmethod=indent
set foldlevel=5
set foldlevelstart=99

" indent折叠命令:
" 操作：za，打开或关闭当前折叠；zM，关闭所有折叠；zR，打开所有折叠
" zc 折叠
" zC 对所在范围内所有嵌套的折叠点进行折叠
" zo 展开折叠
" zO 对所在范围内所有嵌套的折叠点展开
" [z 到当前打开的折叠的开始处。
" ]z 到当前打开的折叠的末尾处。
" zj 向下移动。到达下一个折叠的开始处。关闭的折叠也被计入。
" zk 向上移动到前一折叠的结束处。关闭的折叠也被计入。


EOF
}

function install_config_code_complete()
{
	cat >> ~/.vimrc << EOF

"插件: code_complete
"功能: 快速编辑代码
"用法: 快速建立main函数: 输入main后紧接着按<tab>键
"用法: 头文件插入预编译: 输入ff后紧接着按<tab>键
"用法: 快速插入系统头文件: is<tab>
"用法: 快速插入自定义头文件: in<tab>
"用法: 快速插入if条件: ife3<tab>
"用法: 快速插入switch条件: switch3<tab>
"用法: 快速插入while循环: while<tab>
"用法: 快速插入for循环: for<tab>
"用法: 函数参数补齐提示: 如输入【被调用函数名(】紧接着按<tab>键
"用法: 函数快速定义: 如输入【f3】<tab>表示定义一个三个参数函数
"用法: 快速切换目标: 插入模式下按<tab>键快速切换

EOF
}

function install_config_omnicppcomplete()
{
    # 如果omnicppcomplete官方更新了，需要把该插件放到.vim目录下，否则该插件无法正常工作
	# mv  -v   ${HOME}/.vim/bundle/omnicppcomplete-0.41/after \
	# 		 ${HOME}/.vim/
	# mv  -v   ${HOME}/.vim/bundle/omnicppcomplete-0.41/autoload \
	# 		 ${HOME}/.vim/
	# rm  -rf  ${HOME}/.vim/bundle/omnicppcomplete-0.41

	cat >> ~/.vimrc << EOF

" 插件: omnicppcomplete
" 功能: 主要用该插件的结构体成员补全功能

EOF
}

function install_packed_plugins()
{
    # clean old info
    rm -rf ~/.vim; mkdir -p ~/.vim 2>/dev/null
 
    # unpack package
    unzip -q plugins_in_dotvim.zip -d ~/.vim/ 

    # 为什么插件要压缩成压缩包？
    # 因为有些插件是直接从git上下载，里面含有.git目录，会导致上传后插件内容被删除
    # 而有些插件是经过我们修改适配修复了一些重要问题。
}

function install_tools()
{
	echo "安装主要工具: vim + ctags + cscope ..."
	check_network
	check_retnot_exit ${LINENO} $? 0

	install_vim
	check_retnot_exit ${LINENO} $? 0

	install_ctags_cscope
	check_retnot_exit ${LINENO} $? 0

	echo "安装主要工具: vim + ctags + cscope OK"
}

function install_plugins()
{
	echo "安装各个插件: ..."

	# 解压本地插件包
	install_packed_plugins

	#install_bundle	
	install_config_bundle
	check_retnot_exit ${LINENO} $? 0

	#install_plugin_bundles
	install_plugin_runtimepath
	check_retnot_exit ${LINENO} $? 0

	#install_plugin_github
	install_common_vimrc
	check_retnot_exit ${LINENO} $? 0

	install_config_taglist
	check_retnot_exit ${LINENO} $? 0

	install_config_sourceexplorer
	check_retnot_exit ${LINENO} $? 0

	install_config_nerdtree
	check_retnot_exit ${LINENO} $? 0

	install_config_lookupfile
	check_retnot_exit ${LINENO} $? 0

	install_config_rainbow
	check_retnot_exit ${LINENO} $? 0

	install_config_indentline
	check_retnot_exit ${LINENO} $? 0

	install_config_minibufexpl
	check_retnot_exit ${LINENO} $? 0

	install_config_mark
	check_retnot_exit ${LINENO} $? 0

	install_config_comments
	check_retnot_exit ${LINENO} $? 0

	install_config_code_complete
	check_retnot_exit ${LINENO} $? 0

	install_config_omnicppcomplete
	check_retnot_exit ${LINENO} $? 0

	echo "安装各个插件: OK"
}


# 安装 vim+ctags+cscope 主要工具
check_permission
install_tools;

# 安装插件以及生成vimrc配置
install_plugins;

# 安装工程构建工具
echo "正在编译: vim_project_update.elf ..."
g++ -g -o vim_project_update.elf vim_project_update.cpp \
    ini_config_manager.cpp \
    doubao_semaphore.cpp \
    log_manager.cpp \
    -lpthread \
    -std=c++11
if [[ $? -eq 0 ]];then
    echo "正在编译: vim_project_update.elf OK"
    ${SUDO} mv -v vim_project_update.elf /usr/bin/
fi

